<?php
/**
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2019-2029 上海牛之云网络科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: https://www.niushop.com

 * =========================================================
 */

namespace addon\supermember\admin\controller;

use addon\coupon\model\CouponType;
use addon\platformcoupon\model\PlatformcouponType;
use addon\platformcoupon\model\PlatformcouponType as PlatformcouponTypeModel;
use addon\supermember\model\Config;
use addon\supermember\model\MemberLevelOrder;
use app\model\member\Member;
use app\model\member\MemberLevel;
use app\admin\controller\BaseAdmin;
use Carbon\Carbon;

/**
 * 会员卡
 */
class Membercard extends BaseAdmin
{
    protected $replace = [];    //视图输出字符串内容替换    相当于配置文件中的'view_replace_str'

    public function __construct()
    {
        parent::__construct();
        $this->replace = [
            'SUPERMEMBER_IMG' => __ROOT__ . '/addon/supermember/admin/view/public/img',
            'SUPERMEMBER_CSS' => __ROOT__ . '/addon/supermember/admin/view/public/css',
        ];
    }

    /**
     * 概况
     * @return mixed
     */
    public function index()
    {
        $order = new MemberLevelOrder();
        $yesterday = Carbon::yesterday();

        $data = [
            'yesterday_num' => $order->getOrderCount([  ['order_status', '=', MemberLevelOrder::ORDER_PAY], [ 'pay_time', 'between', [ date_to_time("{$yesterday->year}-{$yesterday->month}-{$yesterday->day} 00:00:00"), date_to_time("{$yesterday->year}-{$yesterday->month}-{$yesterday->day} 23:59:59") ] ] ])['data'],
            'today_num' => $order->getOrderCount([  ['order_status', '=', MemberLevelOrder::ORDER_PAY], [ 'pay_time', 'between', [ date_to_time(date('Y-m-d 00:00:00')), time() ] ] ])['data'],
            'total_num' => $order->getOrderCount([ ['order_status', '=', MemberLevelOrder::ORDER_PAY] ])['data'],
            'yesterday_money' => $order->getOrderSum([ ['order_status', '=', MemberLevelOrder::ORDER_PAY], [ 'pay_time', 'between', [ date_to_time("{$yesterday->year}-{$yesterday->month}-{$yesterday->day} 00:00:00"), date_to_time("{$yesterday->year}-{$yesterday->month}-{$yesterday->day} 23:59:59") ] ] ], 'order_money')['data'],
            'today_money' => $order->getOrderSum([  ['order_status', '=', MemberLevelOrder::ORDER_PAY], [ 'pay_time', 'between', [ date_to_time(date('Y-m-d 00:00:00')), time() ] ] ], 'order_money')['data'],
            'total_money' => $order->getOrderSum([  ['order_status', '=', MemberLevelOrder::ORDER_PAY] ], 'order_money')['data'],
            'has_card_member' => (new Member())->getMemberCount([ ['member_level_type', '=', 1], ['is_delete', '=', 0] ])['data'], // 持有超级会员卡的人数
            'no_has_card_member' => (new Member())->getMemberCount([  ['member_level_type', '=', 0], ['is_delete', '=', 0] ])['data'], // 未持有超级会员卡的人数
            'card_list' => []
        ];

        $member_level_model = new MemberLevel();
        $card_list = $member_level_model->getMemberLevelList([  ['level_type', '=', 1] ], 'level_name,level_id');
        if (!empty($card_list['data'])) {
            foreach ($card_list['data'] as $k => $item) {
                $count = (new Member())->getMemberCount([ ['member_level', '=', $item['level_id'] ], ['is_delete', '=', 0] ]);
                $card_list['data'][$k]['member_num'] = $count['data'];
            }
            array_multisort(array_column($card_list['data'], 'member_num'), SORT_DESC, $card_list['data']);
            $data['card_list'] = $card_list['data'];
        }

        $this->assign('data', $data);
        return $this->fetch('membercard/index',[], $this->replace);
    }

    /**
     * 销售数据统计
     */
    public function salesStatistics()
    {
        if (request()->isAjax()) {
            $start_time = input('start_time', '');
            $end_time = input('end_time', '');

            $order = new MemberLevelOrder();

            $data = [
                'sale_num' => $order->getOrderCount([ ['site_id', '=', $this->site_id], ['order_status', '=', MemberLevelOrder::ORDER_PAY], [ 'pay_time', 'between', [ strtotime($start_time), strtotime($end_time) ] ] ])['data'],
                'sale_money' => $order->getOrderSum([ ['site_id', '=', $this->site_id], ['order_status', '=', MemberLevelOrder::ORDER_PAY], [ 'pay_time', 'between', [ strtotime($start_time), strtotime($end_time) ] ] ], 'order_money')['data'],
            ];

            return success(0, '', $data);
        }
    }

    /**
     * 会员卡列表
     * @return mixed
     */
    public function lists()
    {
        if (request()->isAjax()) {
            $page        = input('page', 1);
            $page_size   = input('page_size', PAGE_LIST_ROWS);
            $search_text = input('search_text', '');

            $condition   = [
                ['level_type', '=', 1]
            ];
            if (!empty($search_text)) $condition[] = ['level_name', 'like', "%" . $search_text . "%"];
            $order       = 'growth asc,level_id desc';
            $field       = '*';

            $member_level_model = new MemberLevel();
            $list               = $member_level_model->getMemberLevelPageList($condition, $page, $page_size, $order, $field);
            if (!empty($list['data']['list'])) {
                $member_model = new Member();
                foreach ($list['data']['list'] as $k => $item) {
                    $count = $member_model->getMemberCount([ ['member_level', '=', $item['level_id'] ], ['is_delete', '=', 0] ]);
                    $list['data']['list'][$k]['member_num'] = $count['data'];
                }
            }
            return $list;
        } else {

            return $this->fetch('membercard/lists');
        }
    }

    /**
     * 添加会员卡
     * @return mixed
     */
    public function add()
    {
        $member_level_model = new MemberLevel();
        if (request()->isAjax()) {
            $data = [
                'site_id'          => $this->site_id,
                'level_name'       => input('level_name', ''),
                'growth'           => input('growth', 0),
                'remark'           => input('remark', ''),
                'is_free_shipping' => input('is_free_shipping', 0),
                'consume_discount' => input('consume_discount', 100),
                'point_feedback'   => input('point_feedback', 0),
                'send_point'       => input('send_point', 0),
                'send_balance'     => input('send_balance', 0),
                'send_coupon'      => input('send_coupon', ''),
                'charge_rule'      => input('charge_rule', ''),
                'charge_type'      => input('charge_type', 0),
                'level_type'      => 1,
                'bg_color' => input('bg_color', ''),
                'cover'=> input('cover', ''),
                'level_price'      => input('level_price', 0),
                'first_content_description'           => input('first_content_description', ''),
                'second_content_description'           => input('second_content_description', ''),
            ];
            $this->addLog("添加会员卡:" . $data['level_name']);
            $res = $member_level_model->addMemberLevel($data);
            return $res;
        } else {

            $this->assign('level_time', $member_level_model->level_time);
            return $this->fetch('membercard/add');
        }
    }

    /**
     * 编辑会员卡
     * @return mixed
     */
    public function edit()
    {
        $member_level_model = new MemberLevel();
        if (request()->isAjax()) {
            $data = [
                'level_name'       => input('level_name', ''),
                'remark'           => input('remark', ''),
                'is_free_shipping' => input('is_free_shipping', 0),
                'consume_discount' => input('consume_discount', 100),
                'point_feedback'   => input('point_feedback', 0),
                'send_point'       => input('send_point', 0),
                'send_balance'     => input('send_balance', 0),
                'send_coupon'      => input('send_coupon', ''),
                'charge_rule'      => input('charge_rule', ''),
                'charge_type'      => input('charge_type', 0),
                'bg_color' => input('bg_color', ''),
                'cover'=> input('cover', ''),
                'coupon_num'=> input('coupon_num', ''),
                'level_price'      => input('level_price', 0),
                'first_content_description'           => input('first_content_description', ''),
                'second_content_description'           => input('second_content_description', ''),
            ];
            $level_id = input('level_id', 0);
            $this->addLog("编辑会员卡:" . $data['level_name']);
            return $member_level_model->editMemberLevel($data, [['level_id', '=', $level_id]]);
        } else {
            $level_id   = input('id', 0);
            $level_info = $member_level_model->getMemberLevelInfo([['level_id', '=', $level_id]]);

            //读取优惠券列表
            if (!isset($level_info['data']['send_coupon'])) $level_info['data']['send_coupon'] = 0;
            $coupon_list = [];
            if($level_info['data']['send_coupon'] != 0 && $level_info['data']['send_coupon'] != '') {
                $coupon = new PlatformcouponType();
                $coupon_list = $coupon->getPlatformcouponTypeList([ ['status','=',1],['platformcoupon_type_id','in',$level_info['data']['send_coupon']] ]);
                $coupon_list = $coupon_list['data'];
            }
            $level_info['data']['coupon_list'] = $coupon_list;
            $this->assign('level_info', $level_info['data']);
            if (empty($level_info['data'])) return $this->error('未获取到会员卡数据', addon_url('supermember://admin/membercard/lists'));
            $this->assign('level_time', $member_level_model->level_time);

            return $this->fetch('membercard/edit');
        }
    }

    /**
     * 会员等级删除
     */
    public function delete()
    {
        if (request()->isAjax()) {
            $level_id = input('level_id', '');
            $member_level_model = new MemberLevel();
            $this->addLog("会员卡删除id:" . $level_id);
            $condition = [
                ['level_id','=',$level_id]
            ];
            return $member_level_model->deleteMemberLevel($condition);
        }
    }

    /**
     * 会员卡状态变更
     */
    public function status(){
        if (request()->isAjax()) {
            $member_level_model = new MemberLevel();
            $level_id = input('level_id', '');
            $status = input('status', 0);
            $res = $member_level_model->editMemberLevel(['status' => $status], [ ['level_id', '=', $level_id] ]);
            return $res;
        }
    }


    /**
     * 会员卡订单
     * @return mixed
     */
    public function order()
    {
        if (request()->isAjax()) {
            $page        = input('page', 1);
            $page_size   = input('page_size', PAGE_LIST_ROWS);
            $status = input('status', '');//订单状态
            $order_no = input('order_no', '');
            $start_time = input('start_time', '');
            $end_time = input('end_time', '');
            $nickname = input('nickname', '');
            $alias = 'mo';
            $join = [

            ];
            $condition   = [

            ];
            if ($status !== '') {
                $condition[] = ['mo.order_status', '=', $status];
            }
            if ($order_no) {
                $condition[] = ['mo.order_no', '=', $order_no];
            }
            if ($nickname) {
                $condition[] = ['mo.nickname', '=', $nickname];
            }
            if ($start_time && !$end_time) {
                $condition[] = ['mo.create_time', '>=', date_to_time($start_time)];
            } elseif (!$start_time && $end_time) {
                $condition[] = ['mo.create_time', '<=', date_to_time($end_time)];
            } elseif ($start_time && $end_time) {
                $condition[] = ['mo.create_time', 'between', [date_to_time($start_time), date_to_time($end_time)]];
            }
            $order = 'mo.create_time desc';
            $field = 'mo.*';
            $level_order = new MemberLevelOrder();
            $data = $level_order->getLevelOrderPageList($condition, $page, $page_size,$field,$order,$alias,$join);
            $list = $data['data']['list'];
            /*foreach ($list as $k=>$v){
                if ($v['site_id']){
                    $shop = model('shop')->getInfo([['site_id','=',$v['site_id']]]);
                    $list[$k]['site_name'] = $shop['site_name'];
                }
            }*/
            $data['data']['list'] = $list;

            return $data;
        } else {

            return $this->fetch('membercard/order');
        }
    }

    /**
     * 会员卡订单详情
     * @return mixed
     */
    public function orderDetail()
    {
        $order_id = input('order_id', '');
        $level_order = new MemberLevelOrder();
        $condition = [
            ['order_id', '=', $order_id],
            ['site_id', '=', $this->site_id]
        ];
        $order = $level_order->getLevelOrderInfo($condition);
        if (empty($order['data'])) return $this->error('未获取到订单数据', addon_url('supermember://admin/membercard/order'));
        $this->assign('order', $order);
        return $this->fetch('membercard/order_detail');
    }

    /**
     * 线下支付
     * @return array
     */
    public function offlinepay(){
        if (request()->isAjax()) {
            $out_trade_no = input('out_trade_no', 0);
            $level_order = new MemberLevelOrder();
            $res  = $level_order->offlinePay($out_trade_no);
            return $res;
        }
    }

    /**
     * 开卡协议
     * @return mixed
     */
    public function agreement(){
        if (request()->isAjax()) {
            //设置注销协议
            $title = input('title', '');
            $content = input('content', '');
            $config_model = new Config();
            return $config_model->setMemberCardDocument($title, $content, 0, 'admin');
        } else {
            //获取注销协议
            $config_model = new Config();
            $document_info = $config_model->getMemberCardDocument(0, 'admin');
            $this->assign('document_info', $document_info);
            return $this->fetch('membercard/agreement');
        }
    }
}